using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using System;
using System.IO;
using System.Linq;

namespace CodRevit.Commands
{
    [Transaction(TransactionMode.Manual)]
    public class DeleteBackupCommand : IExternalCommand
    {
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            try
            {
                // 获取当前文档路径
                string currentPath = commandData.Application.ActiveUIDocument.Document.PathName;
                if (string.IsNullOrEmpty(currentPath))
                {
                    TaskDialog.Show("提示", "请先保存当前文档");
                    return Result.Failed;
                }
                string directory = Path.GetDirectoryName(currentPath);
                // 查找所有备份文件
                var backupFiles = Directory.GetFiles(directory, "*.0*")
                    .Where(f => Path.GetFileName(f).Count(c => c == '.') > 1)
                    .ToList();

                if (!backupFiles.Any())
                {
                    TaskDialog.Show("提示", "未找到备份文件");
                    return Result.Succeeded;
                }

                // 确认删除
                TaskDialogResult result = TaskDialog.Show("确认",
                    $"确定要删除 {backupFiles.Count} 个备份文件吗？",
                    TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No);

                if (result == TaskDialogResult.Yes)
                {
                    int deletedCount = 0;
                    foreach (string file in backupFiles)
                    {
                        try
                        {
                            File.Delete(file);
                            deletedCount++;
                        }
                        catch (Exception ex)
                        {
                            // 继续删除其他文件
                            continue;
                        }
                    }
                    TaskDialog.Show("完成", $"成功删除 {deletedCount} 个备份文件");
                }

                return Result.Succeeded;
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return Result.Failed;
            }
        }
    }
}